<template>
	<view class="ranking-page">
		<!-- 头部 -->
		<headerSlotVue :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-container" @click="closePage()">
					<view class="back-btn">
						<text class="cuIcon-back"></text>
					</view>
					<view class="page-title">
						互助排行榜
					</view>
					<view class="refresh-btn" @click="refreshData">
						<text class="cuIcon-refresh"></text>
					</view>
				</view>
			</template>
		</headerSlotVue>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 错误状态 -->
		<view v-else-if="error" class="error-container">
			<text class="cuIcon-warn error-icon"></text>
			<text class="error-text">{{ error }}</text>
			<button class="retry-btn" @click="initRanking">重试</button>
		</view>

		<!-- 主要内容 -->
		<view v-else class="main-content">
			<!-- Tab栏 -->
			<scroll-view scroll-x class="tab-bar" :scroll-left="tabScrollLeft">
				<view v-for="(tab, index) in tabs" :key="index" 
					class="tab-item" :class="{ active: currentTab === index }" 
					@click="switchTab(index)">
					<text class="tab-name">{{ tab.name }}</text>
					<view v-if="currentTab === index" class="active-line"></view>
				</view>
			</scroll-view>

			<!-- 榜单内容 -->
			<view class="rank-content">
				<view v-for="(tab, index) in tabs" :key="index" v-show="currentTab === index">
					<!-- 榜单卡片 -->
					<view class="rank-card">
						<view class="card-header">
							<view class="header-left">
								<text class="title">{{ tab.data[0].title }}</text>
								<text class="subtitle">{{ tab.data[0].subtitle }}</text>
							</view>
							<view class="header-right">
								<text class="update-time">{{ lastUpdateTime }}</text>
							</view>
						</view>

						<!-- 前三名展示区 -->
						<view class="top-three">
							<!-- 第二名 -->
							<view class="top-user second-place">
								<view class="rank-badge">2</view>
								<view class="avatar-container">
									<image :src="getAvatarUrl(rankings[1] && rankings[1].userId && rankings[1].userId.avatar)" 
										class="avatar" mode="aspectFill" />
									<view v-if="!rankings[1] || !rankings[1].userId || !rankings[1].userId.avatar" class="default-avatar">
										<text class="cuIcon-people"></text>
									</view>
								</view>
								<view class="user-info">
									<text class="user-name">{{ getDisplayName(rankings[1] && rankings[1].userId && rankings[1].userId.nickname) }}</text>
									<text class="user-stats">{{ (rankings[1] && rankings[1].score) || 0 }}</text>
									<text class="stats-label">{{ tab.text }}</text>
								</view>
							</view>

							<!-- 第一名 -->
							<view class="top-user first-place">
								<view class="rank-badge">1</view>
								<view class="crown-icon">
									<text class="cuIcon-medal"></text>
								</view>
								<view class="avatar-container">
									<image :src="getAvatarUrl(rankings[0] && rankings[0].userId && rankings[0].userId.avatar)" 
										class="avatar" mode="aspectFill" />
									<view v-if="!rankings[0] || !rankings[0].userId || !rankings[0].userId.avatar" class="default-avatar">
										<text class="cuIcon-people"></text>
									</view>
								</view>
								<view class="user-info">
									<text class="user-name">{{ getDisplayName(rankings[0] && rankings[0].userId && rankings[0].userId.nickname) }}</text>
									<text class="user-stats">{{ (rankings[0] && rankings[0].score) || 0 }}</text>
									<text class="stats-label">{{ tab.text }}</text>
								</view>
							</view>

							<!-- 第三名 -->
							<view class="top-user third-place">
								<view class="rank-badge">3</view>
								<view class="avatar-container">
									<image :src="getAvatarUrl(rankings[2] && rankings[2].userId && rankings[2].userId.avatar)" 
										class="avatar" mode="aspectFill" />
									<view v-if="!rankings[2] || !rankings[2].userId || !rankings[2].userId.avatar" class="default-avatar">
										<text class="cuIcon-people"></text>
									</view>
								</view>
								<view class="user-info">
									<text class="user-name">{{ getDisplayName(rankings[2] && rankings[2].userId && rankings[2].userId.nickname) }}</text>
									<text class="user-stats">{{ (rankings[2] && rankings[2].score) || 0 }}</text>
									<text class="stats-label">{{ tab.text }}</text>
								</view>
							</view>
						</view>

						<!-- 排行榜列表 -->
						<view class="ranking-list">
							<view class="list-header">
								<view class="rank-col">排名</view>
								<view class="user-col">用户</view>
								<view class="stats-col">{{ tab.text }}</view>
							</view>

							<scroll-view scroll-y class="list-items" :style="{ height: listHeight + 'px' }">
								<view v-for="(ranking, idx) in rankings.slice(3)" :key="idx + 3" 
									class="list-item" :class="{ 'top10': idx < 7 }">
									<view class="list-rank">{{ ranking.rank }}</view>
									<view class="list-user">
										<view class="list-avatar">
											<image :src="getAvatarUrl(ranking.userId && ranking.userId.avatar)" mode="aspectFill" />
											<view v-if="!ranking.userId || !ranking.userId.avatar" class="default-avatar-small">
												<text class="cuIcon-people"></text>
											</view>
										</view>
										<text class="list-name">{{ getDisplayName(ranking.userId && ranking.userId.nickname) }}</text>
									</view>
									<view class="list-stats">{{ ranking.score }}</view>
								</view>
							</scroll-view>
						</view>

						<!-- 当前用户位置 -->
						<view class="current-user-section">
							<view class="current-user">
								<view class="list-rank">{{ userRanking.rank || '--' }}</view>
								<view class="list-user">
									<view class="list-avatar">
										<image :src="getAvatarUrl(userRanking.user && userRanking.user.avatar)" mode="aspectFill" />
										<view v-if="!userRanking.user || !userRanking.user.avatar" class="default-avatar-small">
											<text class="cuIcon-people"></text>
										</view>
									</view>
									<text class="list-name">{{ userRanking.score ? '我的位置' : '未上榜' }}</text>
								</view>
								<view class="list-stats">{{ userRanking.score || 0 }}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 规则说明 -->
		<view class="rule-section">
			<view class="rule-header">
				<text class="rule-title">排行榜规则</text>
			</view>
			<view class="rule-content">
				<view v-for="(rule, idx) in ruleList" :key="idx" class="rule-item">
					<text class="rule-number">{{ idx + 1 }}、</text>
					<text class="rule-text">{{ rule }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import headerSlotVue from '@/components/header-slot.vue';
import { getRaning } from '@/api/home';
import storage from "@/utils/storage.js";
import config from '@/config/config';

export default {
	components: {
		headerSlotVue,
	},
	data() {
		return {
			config,
			currentTab: 0,
			userInfo: {},
			rankings: [],
			userRanking: {},
			loading: false,
			error: null,
			lastUpdateTime: '',
			listHeight: 400,
			tabs: [{
				name: '热心榜',
				text: '接单次数',
				data: [{
					title: '🔥 热心榜',
					subtitle: '本周接单排行',
				}]
			}, {
				name: '需求榜',
				text: '下单次数',
				data: [{
					title: '📋 需求榜',
					subtitle: '本周需求排行',
				}]
			}, {
				name: '活动榜',
				text: '活动排行',
				data: [{
					title: '🎉 活动榜',
					subtitle: '活动参与排行',
				}]
			}],
			ruleList: [
				'每周见证社区"明星"！我们设有三大榜单',
				'热心榜：表彰每周接单助人最多的热心邻居。',
				'需求榜：展示每周下单最活跃的用户。',
				'活动榜：展示每周参与活动最积极的用户。',
				'荣登榜单榜首，让您的热心与活跃，收获社区的认可与回报！',
				'上榜最低单数 10单',
			]
		}
	},
	computed: {
		tabScrollLeft() {
			// 计算tab滚动位置，让当前选中的tab居中
			const tabWidth = 120; // 每个tab的宽度
			return Math.max(0, (this.currentTab - 1) * tabWidth);
		}
	},
	onLoad() {
		this.userInfo = storage.getUserInfo();
		this.calculateListHeight();
		this.initRanking();
	},
	onPullDownRefresh() {
		this.refreshData();
	},
	methods: {
		// 初始化排行榜数据
		async initRanking() {
			if (!this.userInfo || !this.userInfo.community || !this.userInfo.community._id) {
				this.error = '社区信息获取失败，请重新登录';
				return;
			}

			this.loading = true;
			this.error = null;

			try {
				const res = await getRaning({
					type: this.tabs[this.currentTab].name,
					period: 'weekly',
					communityId: this.userInfo.community._id
				});

				if (res.data && res.data.code === 200) {
					this.userRanking = res.data.data && res.data.data.userRanking || {};
					this.rankings = res.data.data && res.data.data.rankings || [];
					this.lastUpdateTime = this.formatTime(new Date());
				} else {
					throw new Error((res.data && res.data.message) || '获取排行榜数据失败');
				}
			} catch (error) {
				console.error('获取排行榜失败:', error);
				this.error = error.message || '网络错误，请重试';
			} finally {
				this.loading = false;
				uni.stopPullDownRefresh();
			}
		},

		// 刷新数据
		refreshData() {
			this.initRanking();
		},

		// 切换Tab
		switchTab(index) {
			if (this.currentTab === index) return;
			this.currentTab = index;
			this.initRanking();
		},

		// 关闭页面
		closePage() {
			uni.navigateBack();
		},

		// 获取头像URL
		getAvatarUrl(avatar) {
			return avatar || config.commonUrl + '/avt.png';
		},

		// 获取显示名称
		getDisplayName(nickname) {
			return nickname || '虚位以待';
		},

		// 格式化时间
		formatTime(date) {
			const now = new Date();
			const diff = now - date;
			const minutes = Math.floor(diff / 60000);
			const hours = Math.floor(diff / 3600000);
			const days = Math.floor(diff / 86400000);

			if (minutes < 1) return '刚刚';
			if (minutes < 60) return `${minutes}分钟前`;
			if (hours < 24) return `${hours}小时前`;
			if (days < 7) return `${days}天前`;
			
			return date.toLocaleDateString();
		},

		// 计算列表高度
		calculateListHeight() {
			const systemInfo = uni.getSystemInfoSync();
			const screenHeight = systemInfo.screenHeight;
			// 减去头部、tab栏、前三名区域、当前用户区域、规则区域的高度
			this.listHeight = screenHeight - 200 - 80 - 300 - 80 - 200;
		}
	}
}
</script>

<style lang="scss" scoped>
.ranking-page {
	min-height: 100vh;
	background: #f5f7fa;
}

/* 头部样式 */
.header-container {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 32rpx;
	width: 100%;
	height: 88rpx;
}

.back-btn, .refresh-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.1);
	transition: all 0.3s ease;
}

.back-btn:active, .refresh-btn:active {
	background: rgba(255, 255, 255, 0.2);
	transform: scale(0.95);
}

.page-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #2C2622;
}

/* 加载状态 */
.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.loading-spinner {
	width: 60rpx;
	height: 60rpx;
	border: 4rpx solid #f3f3f3;
	border-top: 4rpx solid #2575fc;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 20rpx;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.loading-text {
	font-size: 28rpx;
	color: #909399;
}

/* 错误状态 */
.error-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 32rpx;
	text-align: center;
}

.error-icon {
	font-size: 80rpx;
	color: #ff6b6b;
	margin-bottom: 20rpx;
}

.error-text {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 40rpx;
	line-height: 1.5;
}

.retry-btn {
	background: #2575fc;
	color: white;
	border: none;
	border-radius: 50rpx;
	padding: 20rpx 40rpx;
	font-size: 28rpx;
}

/* Tab栏样式 */
.tab-bar {
	white-space: nowrap;
	padding: 20rpx 0;
	background: white;
	border-bottom: 1rpx solid #eee;
}

.tab-item {
	display: inline-block;
	padding: 20rpx 40rpx;
	position: relative;
	transition: all 0.3s ease;
}

.tab-name {
	font-size: 30rpx;
	color: #909399;
	transition: all 0.3s ease;
}

.tab-item.active .tab-name {
	color: #2575fc;
	font-weight: 600;
}

.active-line {
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 60%;
	height: 6rpx;
	background: #2575fc;
	border-radius: 3rpx;
	animation: slideIn 0.3s ease;
}

@keyframes slideIn {
	from { width: 0; }
	to { width: 60%; }
}

/* 榜单内容 */
.rank-content {
	padding: 20rpx;
}

.rank-card {
	background: white;
	border-radius: 20rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
	overflow: hidden;
	animation: fadeInUp 0.6s ease;
}

@keyframes fadeInUp {
	from {
		opacity: 0;
		transform: translateY(30rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.header-left {
	display: flex;
	flex-direction: column;
}

.title {
	font-size: 36rpx;
	font-weight: 700;
	color: #2C2622;
	margin-bottom: 8rpx;
}

.subtitle {
	font-size: 24rpx;
	color: #909399;
}

.update-time {
	font-size: 22rpx;
	color: #c0c4cc;
}

/* 前三名区域 */
.top-three {
	display: flex;
	justify-content: space-around;
	align-items: flex-end;
	padding: 40rpx 20rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.top-user {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
	margin: 0 10rpx;
}

.first-place {
	transform: scale(1.1);
}

.rank-badge {
	position: absolute;
	top: -15rpx;
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: 700;
	font-size: 24rpx;
	color: white;
	z-index: 2;
	box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.2);
}

.first-place .rank-badge {
	background: linear-gradient(135deg, #ffd700, #ffa500);
	width: 80rpx;
	height: 80rpx;
	font-size: 32rpx;
}

.second-place .rank-badge {
	background: linear-gradient(135deg, #c0c0c0, #a9a9a9);
}

.third-place .rank-badge {
	background: linear-gradient(135deg, #cd7f32, #a0522d);
}

.crown-icon {
	position: absolute;
	top: -40rpx;
	font-size: 60rpx;
	color: #ffd700;
	text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.3);
	z-index: 1;
}

.avatar-container {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	border: 6rpx solid white;
	overflow: hidden;
	box-shadow: 0 12rpx 24rpx rgba(0, 0, 0, 0.2);
	position: relative;
	background: white;
	margin-bottom: 20rpx;
}

.first-place .avatar-container {
	width: 140rpx;
	height: 140rpx;
	border: 8rpx solid #ffd700;
}

.avatar {
	width: 100%;
	height: 100%;
}

.default-avatar {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f0f0f0;
	color: #999;
	font-size: 60rpx;
}

.user-info {
	text-align: center;
	padding: 20rpx;
	background: white;
	border-radius: 20rpx;
	width: 100%;
	box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
}

.user-name {
	font-weight: 600;
	font-size: 28rpx;
	margin-bottom: 10rpx;
	color: #2C2622;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.user-stats {
	font-size: 40rpx;
	font-weight: 700;
	color: #2575fc;
	margin-bottom: 8rpx;
}

.stats-label {
	font-size: 22rpx;
	color: #909399;
}

/* 排行榜列表 */
.ranking-list {
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
	margin: 20rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
}

.list-header {
	display: flex;
	padding: 30rpx 20rpx;
	background: #f8f9ff;
	font-weight: 600;
	color: #7f8c8d;
	border-bottom: 1rpx solid #eee;
}

.rank-col {
	width: 100rpx;
	text-align: center;
}

.user-col {
	flex: 3;
	text-align: left;
}

.stats-col {
	flex: 2;
	text-align: center;
}

.list-items {
	background: white;
}

.list-item {
	display: flex;
	padding: 30rpx 20rpx;
	align-items: center;
	border-bottom: 1rpx solid #f5f5f5;
	transition: all 0.3s ease;
}

.list-item:last-child {
	border-bottom: none;
}

.list-item:hover {
	background-color: #f8f9ff;
}

.list-item.top10 {
	background: linear-gradient(135deg, #fff9f0, #fff5e6);
}

.list-rank {
	width: 100rpx;
	text-align: center;
	font-weight: 600;
	font-size: 32rpx;
	color: #7f8c8d;
}

.list-item.top10 .list-rank {
	color: #ff6b6b;
	font-weight: 700;
}

.list-user {
	flex: 3;
	display: flex;
	align-items: center;
}

.list-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	overflow: hidden;
	margin-right: 20rpx;
	border: 4rpx solid #f0f0f0;
	position: relative;
}

.default-avatar-small {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f0f0f0;
	color: #999;
	font-size: 40rpx;
}

.list-name {
	font-weight: 600;
	font-size: 28rpx;
	color: #2C2622;
}

.list-stats {
	flex: 2;
	text-align: center;
	font-weight: 700;
	font-size: 32rpx;
	color: #2575fc;
}

/* 当前用户 */
.current-user-section {
	margin: 20rpx;
}

.current-user {
	display: flex;
	padding: 30rpx 20rpx;
	align-items: center;
	background: linear-gradient(135deg, #e6f0ff, #f0f5ff);
	border-radius: 20rpx;
	border-left: 8rpx solid #2575fc;
	box-shadow: 0 8rpx 24rpx rgba(37, 117, 252, 0.15);
	position: relative;
}

.current-user::before {
	content: "我的位置";
	position: absolute;
	top: -15rpx;
	right: 20rpx;
	background: #2575fc;
	color: white;
	font-size: 20rpx;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-weight: 600;
}

.current-user .list-rank {
	color: #2575fc;
	font-weight: 700;
}

/* 规则说明 */
.rule-section {
	margin: 20rpx;
	padding: 30rpx;
	background: white;
	border-radius: 20rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
}

.rule-header {
	margin-bottom: 30rpx;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #eee;
}

.rule-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #2C2622;
}

.rule-content {
	.rule-item {
		display: flex;
		padding: 15rpx 0;
		line-height: 1.6;
	}

	.rule-number {
		font-weight: 600;
		color: #2575fc;
		margin-right: 10rpx;
		min-width: 40rpx;
	}

	.rule-text {
		font-size: 26rpx;
		color: #666;
		flex: 1;
	}
}

/* 响应式设计 */
@media (max-width: 750rpx) {
	.top-three {
		padding: 30rpx 10rpx;
	}
	
	.avatar-container {
		width: 100rpx;
		height: 100rpx;
	}
	
	.first-place .avatar-container {
		width: 120rpx;
		height: 120rpx;
	}
	
	.user-stats {
		font-size: 32rpx;
	}
	
	.user-name {
		font-size: 24rpx;
	}
}
</style>